package model

import (
	"errors"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type (
	TasksModel struct {
		db *gorm.DB
	}

	Tasks struct {
		Model
		TaskName      string         `gorm:"type:varchar(32);default:''" json:"task_name"`
		TaskType      string         `gorm:"type:varchar(32)" json:"task_type"`
		StationId     string         `gorm:"type:varchar(40);" json:"station_id"`
		Day           int            `gorm:"default:0" json:"day"`
		ModelId       string         `gorm:"type:varchar(40);" json:"model_id"`
		TimeType      string         `gorm:"type:varchar(6)" json:"time_type"` // 日 周 月  day  week month
		Rule          datatypes.JSON `gorm:"not null" json:"rule"`             // 规则 级别
		Level         int            `gorm:"default:0" json:"level"`
		Switch        string         `gorm:"type:varchar(16);default:'enable'" json:"switch"` //enable disable
		ExecTime      string         `gorm:"type:char(8)" json:"exec_time"`
		RunTaskLogId  string         `gorm:"type:varchar(40);default:''" json:"run_task_log_id"` // 最近运行的任务ID
		SubTaskParams datatypes.JSON `json:"sub_task_params"`
	}
)

func NewTasksModel(db *gorm.DB) *TasksModel {
	return &TasksModel{
		db: db,
	}
}

func (m *TasksModel) FindAll() ([]Tasks, error) {
	var result []Tasks
	err := m.db.Find(&result).Error
	if errors.Is(gorm.ErrRecordNotFound, err) {
		return result, nil
	}
	if err != nil {
		return nil, err
	}
	return append([]Tasks{}, result...), nil
}

func (m *TasksModel) Add(data *Tasks) error {
	return m.db.Create(data).Error
}

func (m *TasksModel) Update(id int64, data Tasks) error {
	return m.db.Where("id = ?", id).Save(&data).Error
}

func (m *TasksModel) UpdateMap(id int64, data map[string]interface{}) (int64, error) {
	tx := m.db.Model(&Tasks{}).Where("id = ?", id).Updates(&data)
	err := tx.Error
	return tx.RowsAffected, err
}

func (m *TasksModel) Save(data *Tasks) error {
	return m.db.Save(data).Error
}
func (m *TasksModel) Delete(id int64) error {
	return m.db.Where("id = ?", id).Delete(&Tasks{}).Error
}

func (m *TasksModel) FindById(id int64) (Tasks, error) {
	var taskData Tasks
	err := m.db.Where("id = ?", id).First(&taskData).Error
	return taskData, err
}

func (m *TasksModel) FindTaskByTimeType(timeType string, page, size int) ([]Tasks, error) {
	var resp []Tasks
	session := m.db.Model(Tasks{})
	if timeType != "" {
		session.Where("time_type = ?", timeType)
	}
	err := session.Limit(size).Offset((page - 1) * size).Find(&resp).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []Tasks{}, nil
	}
	return append([]Tasks{}, resp...), err
}
